<template>
  <teleport to="body">
    <transition name="toast-fade">
      <div v-if="visible" :class="['toast', `toast-${type}`]">
        <span class="toast-icon">{{ icon }}</span>
        <span class="toast-message">{{ message }}</span>
        <button class="toast-close" @click="close">×</button>
      </div>
    </transition>
  </teleport>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const props = defineProps({
  message: {
    type: String,
    required: true
  },
  type: {
    type: String,
    default: 'info', // success, error, warning, info
    validator: (value) => ['success', 'error', 'warning', 'info'].includes(value)
  },
  duration: {
    type: Number,
    default: 5000 // 5秒后自动关闭
  }
})

const visible = ref(false)

const icons = {
  success: '✅',
  error: '❌',
  warning: '⚠️',
  info: 'ℹ️'
}

const icon = icons[props.type] || icons.info

const close = () => {
  visible.value = false
}

onMounted(() => {
  visible.value = true
  
  // 自动关闭
  if (props.duration > 0) {
    setTimeout(() => {
      close()
    }, props.duration)
  }
})

// 暴露关闭方法给父组件
defineExpose({
  close
})
</script>

<style scoped>
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 9999;
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 300px;
  max-width: 500px;
  padding: 16px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
}

.toast-success {
  border-left: 4px solid #10b981; /* green-500 */
}

.toast-error {
  border-left: 4px solid #ef4444; /* red-500 */
}

.toast-warning {
  border-left: 4px solid #f59e0b; /* amber-500 */
}

.toast-info {
  border-left: 4px solid #3b82f6; /* blue-500 */
}

.toast-icon {
  font-size: 20px;
  flex-shrink: 0;
}

.toast-message {
  flex: 1;
  font-size: 14px;
  color: #1f2937; /* gray-800 */
  line-height: 1.5;
}

.toast-close {
  appearance: none;
  border: none;
  background: transparent;
  color: #6b7280; /* gray-500 */
  font-size: 24px;
  line-height: 1;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s;
}

.toast-close:hover {
  background: #f3f4f6; /* gray-100 */
  color: #1f2937; /* gray-800 */
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.toast-fade-enter-active,
.toast-fade-leave-active {
  transition: all 0.3s ease;
}

.toast-fade-enter-from {
  transform: translateX(100%);
  opacity: 0;
}

.toast-fade-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

/* 移动端适配 */
@media (max-width: 640px) {
  .toast {
    top: 10px;
    right: 10px;
    left: 10px;
    min-width: auto;
    max-width: none;
  }
}
</style>

